<!DOCTYPE html>


<html lang="zh-CN">
  

    <head>
      <meta charset="utf-8" />
        
      <meta name="description" content="这个人很懒，什么都没留下" />
      
      <meta
        name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1"
      />
      <title>iOS源码阅读——YYWebImage |  DJ Hong&#39;s BLOG</title>
  <meta name="generator" content="hexo-theme-ayer">
      
      <link rel="shortcut icon" href="/favicon.jpg" />
       
<link rel="stylesheet" href="/dist/main.css">

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css"
      />
      
<link rel="stylesheet" href="/css/custom.css">
 
      <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
       
 

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bulma@5.0.1/bulma.min.css"
      />
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.js"></script>

      <!-- mermaid -->
      
      <style>
        .swal2-styled.swal2-confirm {
          font-size: 1.6rem;
        }
      </style>
    <link rel="alternate" href="/atom.xml" title="DJ Hong's BLOG" type="application/atom+xml">
</head>
  </html>
</html>


<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-iOS源码阅读——YYWebImage"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  iOS源码阅读——YYWebImage
</h1>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2018/12/25/iOS%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB%E2%80%94%E2%80%94YYWebImage/" class="article-date">
  <time datetime="2018-12-25T12:07:29.000Z" itemprop="datePublished">2018-12-25</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/iOS/">iOS</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">1.2k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">4 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <p>加载网络图片是项目中比较常见的需求，<code>YYWebImage</code>是Github中比较好用的图片加载开源框架之一。<code>YYWebImage</code>是作者为UIImageView创建的Category，使得UIImageView的实例能够直接调用一个实例方法，就能获取网络图片的功能。</p>
<h2 id="UIImageView-YYWebImage的实例方法"><a href="#UIImageView-YYWebImage的实例方法" class="headerlink" title="UIImageView+YYWebImage的实例方法"></a>UIImageView+YYWebImage的实例方法</h2><p>在<code>UIImageView+YYWebImage</code>列举了5中方法供开发者使用，分别是：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">①- (void)yy_setImageWithURL:(nullable NSURL *)imageURL placeholder:(nullable UIImage *)placeholder;</span><br><span class="line">②- (void)yy_setImageWithURL:(nullable NSURL *)imageURL options:(YYWebImageOptions)options;</span><br><span class="line">③- (void)yy_setImageWithURL:(nullable NSURL *)imageURL</span><br><span class="line">               placeholder:(nullable UIImage *)placeholder</span><br><span class="line">                   options:(YYWebImageOptions)options</span><br><span class="line">                completion:(nullable YYWebImageCompletionBlock)completion;</span><br><span class="line">④- (void)yy_setImageWithURL:(nullable NSURL *)imageURL</span><br><span class="line">               placeholder:(nullable UIImage *)placeholder</span><br><span class="line">                   options:(YYWebImageOptions)options</span><br><span class="line">                  progress:(nullable YYWebImageProgressBlock)progress</span><br><span class="line">                 transform:(nullable YYWebImageTransformBlock)transform</span><br><span class="line">                completion:(nullable YYWebImageCompletionBlock)completion;</span><br><span class="line"></span><br><span class="line">⑤- (void)yy_setHighlightedImageWithURL:(NSURL *)imageURL</span><br><span class="line">                          placeholder:(UIImage *)placeholder</span><br><span class="line">                              options:(YYWebImageOptions)options</span><br><span class="line">                              manager:(YYWebImageManager *)manager</span><br><span class="line">                             progress:(YYWebImageProgressBlock)progress</span><br><span class="line">                            transform:(YYWebImageTransformBlock)transform</span><br><span class="line">                           completion:(YYWebImageCompletionBlock)completion;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>从方法的具体实现中可以看到，①~④的方法实现，都是调用了方法⑤，只是参数传递有所不同。所以我们只需要着重阅读方法⑤的代码实现</p>
<h2 id="具体实现——UIImageView-YYWebImage-m"><a href="#具体实现——UIImageView-YYWebImage-m" class="headerlink" title="具体实现——UIImageView+YYWebImage.m"></a>具体实现——<a target="_blank" rel="noopener" href="https://github.com/ibireme/YYWebImage/blob/master/YYWebImage/Categories/UIImageView%2BYYWebImage.m">UIImageView+YYWebImage.m</a></h2><ol>
<li><p>判断传入的图片链接如果是NSString类型的实例，要先转换为NSURL类型的实例</p>
</li>
<li><p>三目运算，判断<code>YYWebImageManager</code>实例初始化与否，确保初始化完成</p>
</li>
<li><p>_YYWebImageSetter</p>
<ol>
<li>关于<code>_YYWebImageSetter</code>，作者的注解是：Private class used by web image categories.Typically, you should not use this class directly.它是Web图像类别使用的私有类。通常，您不应直接使用此类。</li>
<li>包含2个只读属性、和4个方法<ol>
<li>属性：（NSURL*）imageURL、(int32_t) sentinel</li>
<li>方法：<ol>
<li>-(int32_t)setOperationWithSentinel: url: options: manager: progress: transform: completion:</li>
<li>-(int32_t)cancel</li>
<li>-(int32_t)cancelWithNewURL:</li>
<li>+(dispatch_queue_t)setterQueue</li>
</ol>
</li>
<li><code>objc_getAssociatedObject</code>：通过runtime获取UIImageView的动态属性setter，类型为<code>_YYWebImageSetter</code>。</li>
<li>如果获取到的setter为空，则需要新建一个_YYWebImageSetter实例，并动态关联这个属性。</li>
<li>[setter cancelWithNewURL:imageURL]通过新的图片链接，取消原来的线程操作。实现步骤：<ol>
<li>dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER)如果_lock的信号量值为0，则线程阻塞，不往下执行。否则，信号量-1（初始信号量为1），继续往下执行。</li>
<li>判断 _operation线程是否存在，如果存在，取消这个线程，并置空。</li>
<li>为 _imageURL变量赋值——新的图片连接</li>
<li>sentinel = OSAtomicIncrement32(&amp;_sentinel);值自增</li>
<li>dispatch_semaphore_signal(_lock) 信号量+1</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
<li><p>_yy_dispatch_sync_on_main_queue确保在主线程执行后面的代码。</p>
<ol>
<li>从内存缓存<code>YYImageCacheTypeMemory</code>中获取图片，如果获取成功，则执行complete()，结束操作。</li>
<li>未在内存缓存中获取到图片，继续执行。<ol>
<li>通过 [_YYWebImageSetter setterQueue]，获取到一个与全局队列优先级相同的队列，并异步执行后面的代码</li>
<li>预先创建和实现的  YYWebImageCompletionBlock _completion block。</li>
<li>实现 _YYWebImageSetter *setter的实例方法—— [setter setOperationWithSentinel:sentinel url:imageURL options:options manager:manager progress:_progress transform:transform completion:_completion]。</li>
<li>通过一路追随 _completion block的传递，发现进入了  YYWebImageOperation  类。</li>
<li>YYWebImageOperation继承于 NSOperation。作者重写了NSOpration类的start，方法。并在恰当时机调用了自定义方法 _startOperation。</li>
<li>_startOperation方法的实现<ol>
<li>当_cache存在且用户没有设置  YYWebImageOptionUseNSURLCache 和  YYWebImageOptionRefreshImageCache 选项。会先去取图片缓存。</li>
<li>获取内存图片缓存，调用方法 [_cache getImageForKey:_cacheKey withType:YYImageCacheTypeMemory];。通过_cacheKey获取内存缓存。如果获取成功，结束后台线程；获取失败，则向下执行</li>
<li>当用户没有设置忽略磁盘缓存 YYWebImageOptionIgnoreDiskCache，则接下去，从磁盘获取图片缓存。</li>
<li>获取磁盘图片缓存，调用方法 [self.cache getImageForKey:self.cacheKey withType:YYImageCacheTypeDisk]。<ol>
<li>如果从磁盘获取图片缓存成功，先将图片缓存到内存，并调用 _didReceiveImageFromDiskCache方法。</li>
<li>如果同磁盘获取图片缓存失败，则需要从网络请求图片数据。</li>
</ol>
</li>
<li>通过网络请求获取图片。<ol>
<li>通过 incrementNetworkActivityCount为请求数量+1</li>
<li>通过 connection: didReceiveData: 方法的回调，不断地获取数据。</li>
<li>在 connectionDidFinishLoading 的方法回调中，调用 _didReceiveImageFromWeb 方法。</li>
<li>通过 decrementNetworkActivityCount 为请求数量-1</li>
</ol>
</li>
<li><ol>
<li>_didReceiveImageFromWeb成功从网络获取图片。将图片分别存入内存和磁盘缓存中。</li>
</ol>
</li>
<li>回到之前实现的 _completion代码块。主要是一些动画特效。</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
<li><p>通过<code>completion:(nullable YYWebImageCompletionBlock)completion</code>，将结果返回给开发者</p>
</li>
</ol>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p><code>YYWebImage</code>的实现合乎我们的直觉：</p>
<ul>
<li>查看缓存（1.内存；2.磁盘）<ul>
<li>缓存命中<ul>
<li>返回图片</li>
<li>更新视图</li>
</ul>
</li>
<li>缓存未命中<ul>
<li>异步下载图片</li>
<li>加入缓存</li>
<li>更新视图</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="心得"><a href="#心得" class="headerlink" title="心得"></a>心得</h3><p>之前尝试阅读过<code>YYWebImage</code>框架，当时的方法是一个类一个类看，从.h的属性、方法，到.m的具体实现。说实话，看起来着实有点烧脑和低效。读了<a target="_blank" rel="noopener" href="https://github.com/draveness/analyze">Draven</a>的《<a target="_blank" rel="noopener" href="https://github.com/draveness/analyze/blob/master/contents/SDWebImage/iOS%20%E6%BA%90%E4%BB%A3%E7%A0%81%E5%88%86%E6%9E%90%20---%20SDWebImage.md">iOS 源代码分析 — SDWebImage</a>》，有所启发，直接以API作为入口阅读源码，更具方向性，才会更有收获。<br>文章中涉及到了<a target="_blank" rel="noopener" href="https://www.cnblogs.com/snailHL/p/3906112.html">dispatch_semaphore</a>、<a target="_blank" rel="noopener" href="https://www.jianshu.com/p/8f07a9bdd1cd">队列优先级</a>的知识。</p>
 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          打赏
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=https://hongdongjie.gitee.io/2018/12/25/iOS%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB%E2%80%94%E2%80%94YYWebImage/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/YYWebImage/" rel="tag">YYWebImage</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB/" rel="tag">源码阅读</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2019/08/26/2019%E5%B9%B48%E6%9C%88%E8%AF%BB%E4%B9%A6%E5%BF%83%E5%BE%97/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            2019年8月读书心得
          
        </div>
      </a>
    
    
      <a href="/2018/11/30/iOS-UITableView-%E9%95%BF%E6%8C%89%E7%A7%BB%E5%8A%A8Cell%E7%9A%84%E4%BD%8D%E7%BD%AE/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">iOS UITableView 长按移动Cell的位置</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "evJAWdDwf7wWhHoUPfm3Njb6-gzGzoHsz",
    app_key: "z76x0RgTfVfauSSB6kV2xGUl",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
   
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2018-2022
        <i class="ri-heart-fill heart_icon"></i> GG266
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></span>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
      <li>
          <img src="/images/beian.png"></img>
          <a href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=33010902002204" target="_black" rel="nofollow">浙公网安备 33010902002204号</a>
      </li>
        
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s4.cnzz.com/z_stat.php?id=1280804963&amp;web_id=1280804963'></script>
        
      </li>
    </ul>
  </div>
</footer>    
    </main>
    <div class="float_btns">
      <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

    </div>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="DJ Hong&#39;s BLOG"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about">关于</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="https://gitee.com/hongdongjie/gg266picgo/raw/master/pic4blog/alipay.JPG">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="https://gitee.com/hongdongjie/gg266picgo/raw/master/pic4blog/wechat.JPG">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-3.6.0.min.js"></script>
 
<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->
 
<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: ".tocbot",
    contentSelector: ".article-entry",
    headingSelector: "h1, h2, h3, h4, h5, h6",
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: "main",
    positionFixedSelector: ".tocbot",
    positionFixedClass: "is-position-fixed",
    fixedSidebarOffset: "auto",
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->
 <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script> 
<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->
 
<script src="/js/busuanzi-2.3.pure.min.js"></script>
 
<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->
 
<link rel="stylesheet" href="/css/clipboard.css">
 <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>
 
<!-- CanvasBackground -->

<script>
  if (window.mermaid) {
    mermaid.initialize({ theme: "forest" });
  }
</script>


    
    <div id="music">
    
    
    
    <iframe frameborder="no" border="1" marginwidth="0" marginheight="0" width="200" height="52"
        src="//music.163.com/outchain/player?type=2&id=1908797593&auto=1&height=32"></iframe>
</div>

<style>
    #music {
        position: fixed;
        right: 15px;
        bottom: 0;
        z-index: 998;
    }
</style>
    
    

  </div>
</body>

</html>